<?php

namespace app\model\goods;

use app\base\BaseModel;
use app\libs\Util;
use app\model\activity\ActivityGoodsModel;
use app\model\agency\AgencyGoodsModel;
use app\model\order\OrderItemModel;
use app\model\user\UserCartModel;
use app\model\user\UserCollectUpModel;
use app\model\user\UserModel;
use think\facade\Db;
use think\Image;
use think\model\concern\SoftDelete;

/**
 *
 * 模型-goods
 * Class GoodsCommonModel
 * @package app\model
 */
class GoodsCommonModel extends BaseModel
{
    use SoftDelete;

    protected $name = 'goods_common';

    /**
     * 获取商品属性参数
     * @param $goods_id
     * @param array $attr_ids
     * @param bool $is_storage 库存是否大于0
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCommonGoods($goods_id, $attr_ids = [], $is_storage = false)
    {
        $map = [
            'goods_id' => $goods_id
        ];
        $model = $this;
        if ($is_storage) {
            $model = $model->where('goods_storage', '>', 0);
        }
        if (!empty($attr_ids)) {
            if (is_array($attr_ids)) {
                $map['attribute_ids'] = ['in', $attr_ids];
            } else {
                $map['attribute_ids'] = $attr_ids;
            }
        }
        $common_list = $model->where($map)->select();
        if (empty($common_list)) {
            return [];
        }
        $goods_attr = [];
        foreach ($common_list as $value) {
            $goods_attr[] = [
                'id' => $value['id'],
                'attribute_ids' => $value['attribute_ids'],
                'goods_id' => $value['goods_id'],
                'goods_name' => $value['goods_title'],
                'goods_image' => $value['goods_image'],
                'attribute_names' => $value['attribute_names'],
                'goods_cost_price' => $value['goods_cost_price'],
                'goods_sell_price' => $value['goods_sell_price'],
                'goods_market_price' => $value['goods_market_price'],
                'goods_agency_price' => $value['goods_market_price'],
                'goods_storage' => $value['goods_storage'],
                'goods_limit' => $value['goods_limit'],
                'goods_unit_price' => $value['goods_unit_price'],
                'goods_ratio_price' => $value['goods_ratio_price'],
                'goods_unit' => $value['goods_unit'],
                'goods_unit_number' => $value['goods_unit_number'],
                'bean' => $value['bean'],
                'coupon' => $value['coupon']
            ];
        }
        return $goods_attr;
    }

    /**
     * 获取商品属性参数
     * @param $goods_id
     * @param array $attr_ids
     * @param bool $is_storage 库存是否大于0
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCommonGoodsUserid($goods_id, $attr_ids = [], $user_id = 0, $is_storage = false)
    {
        $map = [
            'goods_id' => $goods_id
        ];
        $model = $this;
        if ($is_storage) {
            $model = $model->where('goods_storage', '>', 0);
        }
        if (!empty($attr_ids)) {
            if (is_array($attr_ids)) {
                $map['attribute_ids'] = ['in', $attr_ids];
            } else {
                $map['attribute_ids'] = $attr_ids;
            }
        }
        $common_list = $model->where($map)->select();
        if (empty($common_list)) {
            return [];
        }
        $goods_attr = [];
        foreach ($common_list as $value) {
            if (empty($user_id)) {
                $goods_number = 0;
            } else {
                $goods_number = UserCartModel::getCartNum($user_id, $value['goods_id'], $value['attribute_ids']);
            }
            $goods_attr[] = [
                'id' => $value['id'],
                'attribute_ids' => $value['attribute_ids'],
                'goods_id' => $value['goods_id'],
                'goods_name' => $value['goods_title'],
                'goods_image' => $value['goods_image'],
                'attribute_names' => $value['attribute_names'],
                'goods_cost_price' => $value['goods_cost_price'],
                'goods_sell_price' => $value['goods_sell_price'],
                'goods_market_price' => $value['goods_market_price'],
                'goods_agency_price' => $value['goods_market_price'],
                'goods_storage' => $value['goods_storage'],
                'goods_limit' => $value['goods_limit'],
                'goods_unit_price' => $value['goods_unit_price'],
                'goods_unit' => $value['goods_unit'],
                'goods_unit_number' => $value['goods_unit_number'],
                'goods_number' => $goods_number,
            ];
        }
        return $goods_attr;
    }


    /**
     * 商品
     * @param $goods_ids
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCommonGoodsIds($goods_ids)
    {
        $common_list = $this->whereIn('goods_id', $goods_ids)->select();
        if (empty($common_list)) {
            return [];
        }
        $goods_attr = [];
        foreach ($common_list as $value) {
            $goods_attr[$value['goods_id']][] = [
                'id' => $value['id'],
                'attribute_ids' => $value['attribute_ids'],
                'goods_id' => $value['goods_id'],
                'goods_name' => $value['goods_title'],
                'goods_image' => $value['goods_image'],
                'attribute_names' => $value['attribute_names'],
                'goods_cost_price' => $value['goods_cost_price'],
                'goods_sell_price' => $value['goods_sell_price'],
                'goods_market_price' => $value['goods_market_price'],
                'goods_agency_price' => $value['goods_market_price'],
                'goods_storage' => $value['goods_storage'],
                'goods_limit' => $value['goods_limit'],
                'goods_unit_price' => $value['goods_unit_price'],
                'goods_ratio_price' => $value['goods_ratio_price'],
                'goods_unit' => $value['goods_unit'],
                'goods_unit_number' => $value['goods_unit_number']
            ];
        }
        return $goods_attr;
    }

    /**
     * 商品价格批量修改
     * @param $goods_ids
     * @param int $ratio
     */
    public function setCommonGoodsIdsPrice($goods_ids, $ratio = 1)
    {
        $goods_ids_str = implode(',', $goods_ids);
        if ($ratio > 0) {
            $sql = "update t_goods_common set goods_sell_price=($ratio*goods_sell_price) where goods_id in($goods_ids_str)";
            Db::execute($sql);
            $sql = "update t_goods set goods_price=($ratio*goods_price) where id in($goods_ids_str)";
            Db::execute($sql);
        } else {
            $ratio = abs($ratio);
            $sql = "update t_goods_common set goods_sell_price=(goods_sell_price/$ratio) where goods_id in($goods_ids_str)";
            Db::execute($sql);
            $sql = "update t_goods set goods_price=(goods_price/$ratio) where id in($goods_ids_str)";
            Db::execute($sql);
        }
    }

    /**
     * 获取商品列表（商品规格id集合）
     * @param string $attribute_ids
     * @param string $field
     * @param int $store_id
     * @return array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCommonAttrIdIn($attribute_ids = '', $field = 'a.*')
    {
        $goods_list = $this->alias('a')
            ->leftJoin("t_goods g", "g.id=a.goods_id")
            ->whereIn('attribute_ids', $attribute_ids)
            ->field($field)->select();
        if (empty($goods_list)) {
            return [];
        }
        return $goods_list;
    }

    /**
     * @param $attribute_ids
     * @param $keyword
     * @param int $page
     * @param int $limit
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getAttrIdNotInPage($attribute_ids, $keyword, $page = 1, $limit = 10)
    {
        $goods_list = $this->alias('a')
            ->join("t_goods g", "g.id=a.goods_id")
            ->where('a.goods_storage', '>', 0)
            ->where('g.delete_time', '=', 0)
            ->whereLike('a.goods_title', "%$keyword%")
            ->whereNotIn('a.attribute_ids', implode(',', $attribute_ids))
            ->paginate(['page' => $page, 'list_rows' => $limit], false);
        return $goods_list;
    }

    /**
     * 获取商品信息（商品规格id集合）
     * @param string $attribute_ids
     * @param string $field
     * @param int $store_id
     * @return array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCommonAttrId($attribute_ids = '', $field = 'a.*,g.*')
    {
        $goods_data = $this->alias('a')
            ->leftJoin("t_goods g", "g.id=a.goods_id")
            ->where('attribute_ids', $attribute_ids)
            ->field($field)->find();
        if (empty($goods_data)) {
            return [];
        }
        return $goods_data;
    }

    /**
     * 获取商品商品拓展信息列表
     * @param $goods_id
     * @param array $attribute_ids
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAttrList($goods_id, $attribute_ids = [])
    {
        $goods_attr_model = new GoodsAttributeModel();
        $attr_list = $goods_attr_model->where(['goods_id' => $goods_id])->select();
        if (empty($attr_list)) {
            return [];
        }
        $attr_list_return = [];
        $goods_attr_value_model = new GoodsAttributeValueModel();
        foreach ($attr_list as $value) {
            $list_temp = $goods_attr_value_model->getList(['attribute_id' => $value['id']]);
            $list = [];
            foreach ($list_temp as $v) {
                $selected = in_array(intval($v['id']), $attribute_ids);
                $list[] = [
                    'id' => $v['id'],
                    'name' => $v['name'],
                    'selected' => $selected
                ];
            }
            $attr_list_return[] = [
                'id' => $value['id'],
                'name' => $value['name'],
                'list' => $list
            ];
        }
        return $attr_list_return;
    }

    /**
     * 删除商品拓展信息（设置库存为0）
     * @param $goods_ids
     * @param $is_soft
     * @return bool
     */
    public function delCommon($goods_ids, $is_soft = false)
    {
        if (is_array($goods_ids)) {
            $map = ['goods_id' => ['in', $goods_ids]];
        } else {
            $map = ['goods_id' => $goods_ids];
        }
        if ($is_soft) {
            $ret = $this->where($map)->update(['goods_storage' => 0]);
        } else {
            $ret = $this->where($map)->delete();
        }
        if ($ret !== false) {
            $this->_upGoodsStorage($goods_ids);
            return true;
        }
        return false;
    }

    /**
     * 清空指定商品的库存
     * @param $goods_id
     * @param $ids
     * @return bool
     */
    public function delStorage($goods_id, $ids)
    {
        $map = ['goods_id' => $goods_id];
        if (is_array($ids)) {
            $map['attribute_ids'] = ['in', $ids];
        } else {
            $map['attribute_ids'] = $ids;
        }
        $ret = $this->where($map)->update(['goods_storage' => 0]);
        if ($ret !== false) {
            $this->_upGoodsStorage($goods_id);
            return true;
        }
        return false;
    }

    /**
     * 跟新商品库存
     * @param $goods_id
     * @param $attribute_ids
     * @param $goods_storage
     * @return bool
     */
    public function changeStore($goods_id, $attribute_ids, $goods_storage)
    {
        $ret = $this->where(['goods_id' => $goods_id, 'attribute_ids' => $attribute_ids])->update(['goods_storage' => $goods_storage]);
        if ($ret !== false) {
            $this->_upGoodsStorage($goods_id);
            return true;
        }
        return false;
    }

    /**
     * 刷新商品库存
     * @param string $goods_id
     * @return bool
     */
    private function _upGoodsStorage($goods_id = "")
    {
        $ret = false;
        if (is_array($goods_id)) {
            foreach ($goods_id as $value) {
                $storage = $this->where(['goods_id' => $value])->sum('goods_storage');
                $goods_model = new GoodsModel();
                $ret = $goods_model->where(['id' => $value])->update(['goods_storage' => $storage]);
            }
        } else {
            $storage = $this->where(['goods_id' => $goods_id])->sum('goods_storage');
            $goods_model = new GoodsModel();
            $ret = $goods_model->where(['id' => $goods_id])->update(['goods_storage' => $storage]);
        }
        if ($ret !== false) {
            return true;
        }
        return false;
    }
}
